<template>
  <div class="app-container">
    <div id="container"></div>

    <div class="box">
      <div class="charts">
        <div class="bchart">
          <Chartone
            id="Chartone"
            width="100%"
            height="100%"
            :studentnumber_list="studentnumberarr"
            :teachernumber_list="teachernumberarr"
            :schoolname_list="schoolnamearr"
          ></Chartone>
        </div>
        <div class="rchart">
          <Charttwo
            id="Charttwo"
            width="100%"
            height="100%"
            :schoolname_list="schoolnamearr"
            :area_list="schoolareaarr"
          ></Charttwo>
        </div>
      </div>
      <div class="traffic_box">
        <el-row>
          <el-button type="primary" @click="clickOn()" class="btn" size="small"
            >标记点</el-button
          ><->
          <el-select
            v-model="value_schoolsite"
            placeholder="请选择"
            class="select"
            size="mini"
          >
            <el-option
              v-for="item in schoolname_and_schoolsite"
              :key="item.schoolname"
              :label="item.schoolname"
              :value="item.schoolsite"
            >
            </el-option>
          </el-select>
        </el-row>
        <el-row>查询规划路线</el-row>
        <el-row>
          <el-button
            type="primary"
            @click="walk(this)"
            size="mini"
            class="smallbtn"
            >步行</el-button
          >
          <el-button
            type="primary"
            @click="ride(this)"
            size="mini"
            class="smallbtn"
            >骑行</el-button
          >
          <el-button
            type="primary"
            @click="drive(this)"
            size="mini"
            class="smallbtn"
            >驾车</el-button
          >
          <el-button
            type="primary"
            @click="bus(this)"
            size="mini"
            class="smallbtn"
            >公交</el-button
          >
        </el-row>
        <el-row>
          <el-button
            type="primary"
            @click="deletetraffic(this)"
            size="small"
            class="smallbtn"
            >删除规划路线</el-button
          >
        </el-row>
      </div>
      <div id="panel" ref="panel"></div>
    </div>
  </div>
</template>

<script>
import { getinfo, getschoolinfo } from "@/api/school";
import Chartone from "@/components/chartone.vue";
import Charttwo from "@/components/charttwo.vue";

export default {
  name: "user",
  components: { Chartone, Charttwo },
  data() {
    return {
      map: null,
      value_schoolsite: null,
      // 家长定位的经纬度,为数组
      lnglat: [],
      // 家长定位的标记点
      smarker: null,
      walking: null,
      riding: null,
      driving: null,
      transfer: null,
      echart_schoolname_list: [],
      echart_studentnumber_list: [],
      echart_teachernumber_list: [],
      echart_area_list: [],
      blockzonearr: [],
      block_namearr: [],
      schoolnamearr: [],
      schoolsitearr: [],
      teachernumberarr: [],
      studentnumberarr: [],
      schoolareaarr: [],
      schoolname_and_schoolsite: [],
      timer: null,
    };
  },
  created() {
    this.getinfo();
    this.timer = setInterval(() => {
      getschoolinfo().then((res) => {
        let resultss = res.data.result;
        this.teachernumberarr = [];
        this.studentnumberarr = [];
        this.schoolareaarr = [];
        for (let i = 0; i < resultss.length; i++) {
          this.teachernumberarr.push(resultss[i].teachernumber);
          this.studentnumberarr.push(resultss[i].studentnumber);
          this.schoolareaarr.push(resultss[i].schoolarea);
        }
        console.log(this.studentnumberarr);
      });
    }, 3000);
  },
  computed: {
    // ...mapState(["cityname", "provincename"]),
  },
  methods: {
    getinfo() {
      getinfo()
        .then((res) => {
          console.log(res);
          console.log(res.data.result);
          let results = res.data.result;
          for (let i = 0; i < results.length; i++) {
            this.block_namearr.push(results[i].school);
            let path = "";
            let arr = [];
            path = results[i].blockzone.substr(
              1,
              results[i].blockzone.length - 2
            );
            path = path.split("/");
            path.forEach((item) => {
              let a = item.substr(1, item.length - 2);
              let ar = a.split(",");
              arr.push(ar);
            });
            this.blockzonearr.push(arr);
          }
          return getschoolinfo();
        })
        .then((res) => {
          console.log(res);
          let resultss = res.data.result;
          console.log(resultss);
          for (let i = 0; i < resultss.length; i++) {
            // cen为[112.404259,23.606126]形式的字符串形式，需要转换成数组
            let cen = resultss[i].schoolsite;
            let cenn = cen.substr(1, cen.length - 2);
            let cennn = cenn.split(",");
            // 把所有学校的中心坐标放在centerarr数组里
            this.schoolsitearr.push(cennn);
            let obj = {
              schoolname: resultss[i].schoolname,
              schoolsite: resultss[i].schoolsite,
            };
            this.schoolname_and_schoolsite.push(obj);
            // let sch = resultss[i].schoolname;
            // 把所有学校的名字放在schoolnamearr数组里
            this.schoolnamearr.push(resultss[i].schoolname);
            this.teachernumberarr.push(resultss[i].teachernumber);
            this.studentnumberarr.push(resultss[i].studentnumber);
            this.schoolareaarr.push(resultss[i].schoolarea);
          }
          this.initAMap();
        });
    },
    initAMap() {
      this.map = new AMap.Map("container", {
        resizeEnable: true,
        layers: [
          // 卫星
          new AMap.TileLayer(),
        ],
        zoom: 13,
        // 设置进入地图，中心为佛山
        // center: [113.11, 23.05],
      });
      // patharr 和 centerarr
      for (let i = 0; i < this.blockzonearr.length; i++) {
        this.createPolyandmark(this.blockzonearr[i], this.block_namearr[i]);
      }
      for (let i = 0; i < this.schoolsitearr.length; i++) {
        this.createschool(this.schoolsitearr[i], this.schoolnamearr[i]);
      }

      this.map.setFitView();
    },
    // 回显片区范围折现
    createPolyandmark(path, school) {
      if (school === "第一中学") {
        let polygon = new AMap.Polygon({
          path: path,
          strokeColor: "#FF33FF",
          strokeWeight: 1,
          strokeOpacity: 0,
          fillOpacity: 0.4,
          fillColor: "#1791fc",
          zIndex: 50,
          bubble: true,
        });
        this.map.add([polygon]);
      } else if (school === "第二中学") {
        let polygon = new AMap.Polygon({
          path: path,
          strokeColor: "#FF33FF",
          strokeWeight: 1,
          strokeOpacity: 0,
          fillOpacity: 0.4,
          fillColor: "#B22222",
          zIndex: 50,
          bubble: true,
        });
        this.map.add([polygon]);
      } else if (school === "第三中学") {
        let polygon = new AMap.Polygon({
          path: path,
          strokeColor: "#FF33FF",
          strokeWeight: 1,
          strokeOpacity: 0,
          fillOpacity: 0.4,
          fillColor: "#00FF00",
          zIndex: 50,
          bubble: true,
        });
        this.map.add([polygon]);
      } else if (school === "第四中学") {
        let polygon = new AMap.Polygon({
          path: path,
          strokeColor: "#9932CC",
          strokeWeight: 1,
          strokeOpacity: 0,
          fillOpacity: 0.4,
          fillColor: "#9932CC",
          zIndex: 50,
          bubble: true,
        });
        this.map.add([polygon]);
      }
    },
    // 回显学校名字和学校坐标
    createschool(centre, schoolname) {
      let marker = new AMap.Marker({
        position: centre, //基点位置
        icon: new AMap.Icon({
          image:
            "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png",
          size: new AMap.Size(25, 34), //图标所处区域大小
          imageSize: new AMap.Size(25, 34), //图标大小
        }),
        offset: new AMap.Pixel(-13, -30), //相对于基点的偏移位置
        // anchor: "bottom-center",
        cursor: "auto",
      });
      // 设置label标签
      // label默认蓝框白底左上角显示，样式className为：amap-marker-label
      marker.setLabel({
        direction: "top",
        offset: new AMap.Pixel(0, 0), //设置文本标注偏移量
        content: `<div class='info'>${schoolname}</div>`, //设置文本标注内容
      });
      marker.setMap(this.map);
    },

    clickOn() {
      this.map.on("click", this.showInfoClick);
      this.maponclick = true;
      this.$message({
        message: "绑定事件成功",
        type: "success",
      });
    },
    showInfoClick(e) {
      // e.lnglat是一个对象，里面有经度和纬度两个属性，要获取这两个属性，需要通过get方法
      // this.lnglat = e.lnglat.getLng() + "," + e.lnglat.getLat();
      this.lnglat = [];
      this.lnglat.push(e.lnglat.getLng());
      this.lnglat.push(e.lnglat.getLat());
      if (this.smarker == null) {
        this.smarker = new AMap.Marker({
          position: [e.lnglat.getLng(), e.lnglat.getLat()], //基点位置
          icon: new AMap.Icon({
            image:
              "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
            size: new AMap.Size(25, 34), //图标所处区域大小
            imageSize: new AMap.Size(25, 34), //图标大小
          }),
          offset: new AMap.Pixel(-13, -15), //相对于基点的偏移位置
          // 设置是否可以拖拽
          draggable: true,
          cursor: "move",
        });
        this.smarker.setMap(this.map);
        console.log(this.lnglat);
        // 监控标记点
        this.smarker.on("dragging", this.dragMarker);
        // return;
      }
      this.smarker.setPosition([e.lnglat.getLng(), e.lnglat.getLat()]); //更新点标记位置
      console.log(this.lnglat);
    },
    dragMarker() {
      // 获取标记点当前位置，并赋值给全局变量lnglat
      // this.marker.setPosition([e.lnglat.getLng(), e.lnglat.getLat()]); //更新点标记位置
      var l = this.smarker.getPosition();
      this.lnglat = [];
      this.lnglat.push(l.getLng());
      this.lnglat.push(l.getLat());
      console.log(this.lnglat);
    },

    walk() {
      // 将面板清空
      this.$refs.panel.innerHTML = "";
      if (this.walking) {
        this.walking.clear();
      }
      if (this.riding) {
        this.riding.clear();
      }
      if (this.driving) {
        this.driving.clear();
      }
      if (this.transfer) {
        this.transfer.clear();
      }
      // 把学校的坐标由字符串改成数组形式
      let cenn = this.value_schoolsite.substr(
        1,
        this.value_schoolsite.length - 2
      );
      let schoolsite = cenn.split(",");
      // 删除我们移动那个标记点
      if (this.smarker) {
        this.smarker.setMap(null);
        this.smarker = null;
        this.map.off("click", this.showInfoClick);
      }
      //步行导航
      let that = this;
      this.walking = new AMap.Walking({
        map: this.map,
        panel: "panel",
      });
      //根据起终点坐标规划步行路线
      this.walking.search(this.lnglat, schoolsite, function (status, result) {
        // result即是对应的步行路线数据信息，相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_WalkingResult
        if (status === "complete") {
          that.$message({
            message: "绘制步行路线完成",
            type: "success",
          });
        } else {
          that.$message.error("步行路线数据查询失败" + result);
        }
      });
    },
    ride() {
      // 将面板清空
      this.$refs.panel.innerHTML = "";
      if (this.walking) {
        this.walking.clear();
      }
      if (this.riding) {
        this.riding.clear();
      }
      if (this.driving) {
        this.driving.clear();
      }
      if (this.transfer) {
        this.transfer.clear();
      }
      // 把学校的坐标由字符串改成数组形式
      let cenn = this.value_schoolsite.substr(
        1,
        this.value_schoolsite.length - 2
      );
      let schoolsite = cenn.split(",");
      // 删除我们移动那个标记点
      if (this.smarker) {
        this.smarker.setMap(null);
        this.smarker = null;
        this.map.off("click", this.showInfoClick);
      }
      let that = this;
      //骑行导航
      this.riding = new AMap.Riding({
        map: this.map,
        panel: "panel",
      });
      //根据起终点坐标规划骑行路线
      this.riding.search(this.lnglat, schoolsite, function (status, result) {
        // result即是对应的骑行路线数据信息，相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_RidingResult
        if (status === "complete") {
          // console.log(result.routes[0]);
          // console.log(result.routes[0].time);
          that.$message({
            message: "绘制骑行路线完成",
            type: "success",
          });
        } else {
          that.$message.error("骑行路线数据查询失败" + result);
        }
      });
    },
    drive() {
      // 将面板清空
      this.$refs.panel.innerHTML = "";
      if (this.walking) {
        this.walking.clear();
      }
      if (this.riding) {
        this.riding.clear();
      }
      if (this.driving) {
        this.driving.clear();
      }
      if (this.transfer) {
        this.transfer.clear();
      }
      // 把学校的坐标由字符串改成数组形式
      let cenn = this.value_schoolsite.substr(
        1,
        this.value_schoolsite.length - 2
      );
      let schoolsite = cenn.split(",");
      // 删除我们移动那个标记点
      if (this.smarker) {
        this.smarker.setMap(null);
        this.smarker = null;
        this.map.off("click", this.showInfoClick);
      }
      let that = this;
      //构造路线导航类
      this.driving = new AMap.Driving({
        map: this.map,
        panel: "panel",
      });
      // 根据起终点经纬度规划驾车导航路线
      this.driving.search(this.lnglat, schoolsite, function (status, result) {
        // result 即是对应的驾车导航信息，相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
        if (status === "complete") {
          that.$message({
            message: "绘制驾车路线完成",
            type: "success",
          });
        } else {
          that.$message.error("获取驾车数据失败" + result);
        }
      });
    },
    bus() {
      // 将面板清空
      let that = this;
      this.$refs.panel.innerHTML = "";
      if (this.walking) {
        this.walking.clear();
      }
      if (this.riding) {
        this.riding.clear();
      }
      if (this.driving) {
        this.driving.clear();
      }
      if (this.transfer) {
        this.transfer.clear();
      }
      // 把学校的坐标由字符串改成数组形式
      let cenn = this.value_schoolsite.substr(
        1,
        this.value_schoolsite.length - 2
      );
      let schoolsite = cenn.split(",");
      // 删除我们移动那个标记点
      if (this.smarker) {
        this.smarker.setMap(null);
        this.smarker = null;
        this.map.off("click", this.showInfoClick);
      }
      let transOptions = {
        map: this.map,
        city: "广州市",
        panel: "panel",
        //cityd:'乌鲁木齐',
        policy: AMap.TransferPolicy.LEAST_TIME,
      };
      //构造公交换乘类
      this.transfer = new AMap.Transfer(transOptions);
      //根据起、终点坐标查询公交换乘路线
      this.transfer.search(this.lnglat, schoolsite, function (status, result) {
        // result即是对应的公交路线数据信息，相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_TransferResult
        if (status === "complete") {
          that.$message({
            message: "绘制公交路线完成",
            type: "success",
          });
        } else {
          that.$message.error("公交路线数据查询失败" + result);
        }
      });
    },
    deletetraffic() {
      this.$refs.panel.innerHTML = "";
      if (this.walking) {
        this.walking.clear();
      }
      if (this.riding) {
        this.riding.clear();
      }
      if (this.driving) {
        this.driving.clear();
      }
      if (this.transfer) {
        this.transfer.clear();
      }
      this.lnglat = [];
      if (this.smarker) {
        this.smarker.setMap(null);
        this.smarker = null;
        this.map.off("click", this.showInfoClick);
      }
    },
  },
};
</script>

<style scoped>
.app-container {
  /* width: 100%;
  height: 100%; */
  position: relative;
}
#container {
  width: 100%;
  height: 620px;
}
.box {
  /* margin-top: 20px; */
  width: 240px;
  height: 100%;
  /* background-color: white; */
  background: linear-gradient(white, rgb(145, 200, 246));
  position: absolute;
  top: 0;
  right: 0;
  /* padding-left: 10px; */
}
.traffic_box {
  padding-left: 10px;
  margin-top: 20px;
  /* position: relative; */
}
.btn {
  margin-bottom: 5px;
}
#panel {
  position: absolute;
  /* background-color: white; */
  /* border: 1px solid blueviolet; */
  overflow-y: auto;
  height: 265px;
  width: 240px;
  /* top: 130px; */
  bottom: 0;
  /* right: 230px; */
  /* z-index: 4; */
}
.amap-marker-label {
  border: 0;
  background-color: transparent;
}
.smallbtn {
  margin-top: 5px;
  margin-left: 0px;
}
.select {
  width: 120px;
}
.charts {
  width: 240px;
  height: 170px;
}
.bchart {
  float: left;
  width: 240px;
  height: 120px;
  /* background-color: yellow; */
  /* margin-top: 20px; */
}
.rchart {
  float: left;
  width: 240px;
  height: 100px;
  /* background-color: red; */
  /* margin-top: 20px; */
}
</style>